package com.runningrookie.service.impl;

import com.runningrookie.annotation.ConcurrencyLock;
import com.runningrookie.domain.AjaxResult;
import com.runningrookie.domain.OrderInfoBean;
import com.runningrookie.mapper.OrderInfoMapper;
import com.runningrookie.service.ConcurrencyLockService;
import com.runningrookie.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class OrderInfoServiceImpl implements OrderInfoService {
    ConcurrencyLockService concurrencyLockService;
    OrderInfoMapper orderInfoMapper;
    @Autowired
    OrderInfoServiceImpl(ConcurrencyLockService concurrencyLockService, OrderInfoMapper orderInfoMapper) {
        this.concurrencyLockService = concurrencyLockService;
        this.orderInfoMapper = orderInfoMapper;
    }
    @Override
    public AjaxResult saveOrderInfo(OrderInfoBean bean) {
        long threadId = Thread.currentThread().getId();
        final String businessNode = "插入";
        Boolean isSuccessLock = concurrencyLockService.tryLock(businessNode, bean.getOrderNo());
        if (!isSuccessLock) {
            return AjaxResult.error("加锁失败，请稍后重试");
        }
        try {
            log.info("{}开始执行业务逻辑", threadId);
            OrderInfoBean orderInfoBean = orderInfoMapper.selectOrderInfoByOrderNo(bean.getOrderNo());
            if (orderInfoBean == null) {
                orderInfoMapper.insertOrderInfo(bean);
            } else {
                bean.setItemQty(bean.getItemQty() + orderInfoBean.getItemQty());
                bean.setId(orderInfoBean.getId());
                orderInfoMapper.updateOrderInfo(bean);
            }
        } finally {
            concurrencyLockService.unLock(businessNode, bean.getOrderNo());
        }
        return AjaxResult.success();
    }
    @Override
    @ConcurrencyLock(businessNode = "插入", businessUniqueNoKey = "orderNo")
    @Transactional
    public AjaxResult saveOrderInfoByAnnotation(OrderInfoBean bean) {
        OrderInfoBean orderInfoBean = orderInfoMapper.selectOrderInfoByOrderNo(bean.getOrderNo());
        if (orderInfoBean == null) {
            orderInfoMapper.insertOrderInfo(bean);
        } else {
            bean.setItemQty(bean.getItemQty() + orderInfoBean.getItemQty());
            bean.setId(orderInfoBean.getId());
            orderInfoMapper.updateOrderInfo(bean);
        }
        return AjaxResult.success();
    }
}
